<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

</body>
<script>
  let result = {}

  const obj = {
    age: 20,
    name: 'vvg',
    address: {
      city: 'zhuhai'
    },
    girlfriend: ['a', 'b', 'c']
  }
  /* 浅拷贝
    const obj1 = obj

    obj1.name = 'czw'

    console.log(obj.name)
   */

  const obj2 = deepClone(obj)
  obj2.name = 'czw'
  console.log(obj.name)
  console.log(obj2.name, '拷贝后')
  console.log(obj2, '拷贝后')

  function deepClone(obj = {}) {
    if (typeof obj !== 'object' || obj == null) {
      //obj是null，或者不是对象和数组，直接返回
      return obj
    }
    //初始化result
    let result
    if (obj instanceof Array) {
      result = []
    } else {
      result = {}
    }

    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        result[key] = deepClone(obj[key])
      }
    }

    return result
  }
</script>

</html>